<?php
namespace LP\tbke;
use Autoloader;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Redis;
use TopClient;
use TbkUatmFavoritesGetRequest;
use TbkUatmFavoritesItemGetRequest;

class TaoBaoKe {
    public static $appkey;
    public static $secretKey;
    public static $TopClient;
    public static $zoneId;
    public $goods_page = 1;
    public $cache_key_menu_list = "menu_list"; //type_id favorites_id

	public function __construct()
    {
        require('TopSdk.php');
        if(!self::$appkey){
            self::$appkey = Config::get('tbke.app_key');
        }
        if(!self::$secretKey){
            self::$secretKey = Config::get('tbke.app_secrect');
        }

        if(!self::$TopClient){
            self::$TopClient = new TopClient();
        }
        if(!self::$zoneId){
            self::$zoneId = Config::get('tbke.adzoneid.bestxiangyang');
        }

    }
    /**
     * 设置网站分类id 与淘宝客之间的关系
     * @param $class_arr 网站处理好的分类
     */
    public function setTypeRelationToTbke($class_arr)
    {
        //淘宝客分类
        $favorites_lists = $this->getFavoritesIds($page_size = '20',$page ='1', $type = '-1');
        foreach($favorites_lists as $key=>$favorites_list){
            $favorites_id = intval($favorites_list['favorites_id']);  //id
            $favorites_title = trim($favorites_list['favorites_title']); //类别标题
            $type = $favorites_list['type']; //选品库类型，1：普通选品组，2：高佣选品组，-1，同时输出所有类型的选品组
            foreach($class_arr as $key1=>$value1){
                foreach($value1['class2'] as $key2=>$value2){
                    foreach($value2['class3'] as $key3=>$value3){
                        if(trim($value3['gc_name']) == trim($favorites_title)){
                            $type_id_favorites_id[$key1][] = $favorites_id;
                            $type_id_favorites_id[$key2][] = $favorites_id;
                            $type_id_favorites_id[$key3][] = $favorites_id;
                            continue;
                        }
                    }
                }
            }
        }
        $cache_key = $this->cache_key_menu_list;
        $cache_value = json_encode($this->objectToArray($type_id_favorites_id));
        return Redis::set($cache_key,$cache_value);
    }

    public function setTypeRelationToTbke_bak($class_arr)
    {
        //淘宝客分类
        $c = $this->setPublic();

        $req = new TbkUatmFavoritesGetRequest;
        $page = '1';
        $page_size = '200';
        $req->setPageNo($page);
        $req->setPageSize($page_size);
        $req->setFields("favorites_title,favorites_id,type");
        $req->setType("-1");
        $resp = $c->execute($req);
        $favorites_lists = $resp->results->tbk_favorites; //选品库相当于库存
        $type_id_favorites_id = array();  //gc_id 与favorites_id之间的关系
        $total = $resp->total_results; //总条数

        foreach($favorites_lists as $key=>$favorites_list){
            $favorites_id = intval($favorites_list->favorites_id);  //id
            $favorites_title = trim($favorites_list->favorites_title); //类别标题
            $type = $favorites_list->type; //选品库类型，1：普通选品组，2：高佣选品组，-1，同时输出所有类型的选品组
            foreach($class_arr as $key1=>$value1){
                foreach($value1['class2'] as $key2=>$value2){
                    foreach($value2['class3'] as $key3=>$value3){
                        if(trim($value3['gc_name']) == trim($favorites_title)){
                            $type_id_favorites_id[$key1][] = $favorites_id;
                            $type_id_favorites_id[$key2][] = $favorites_id;
                            $type_id_favorites_id[$key3][] = $favorites_id;
                            continue;
                        }
                    }
                }
            }
        }
        $cache_key = $this->cache_key_menu_list;
        $cache_value = json_encode($this->objectToArray($type_id_favorites_id));
        return Redis::set($cache_key,$cache_value);
    }

    /**
     * @return TopClient
     */
    protected function setPublic()
    {
        $c = self::$TopClient;
        $c->appkey = self::$appkey;
        $c->secretKey = self::$secretKey;
        return $c;
    }
    /**
     * 设置网站分类id 与淘宝客之间的关系
     * @param $class_arr 网站处理好的分类
     */
    public function getGoodsByTypeId($type_id,$page_no = '1',$page_size = '20',$platform = '1',$zone_id='')
    {

        $cache_key = 'goods_list'.$type_id.$platform.$zone_id;

        if(Redis::exists($cache_key)){
            $data = Redis::get($cache_key);
            if(!empty($data)){
                return unserialize($data);
            }
        }
        $menu_list = json_decode(Redis::get($this->cache_key_menu_list),true);

        if(isset($menu_list[$type_id])){
            $favorites_id_arr = $menu_list[$type_id];
        }else{
            $favorites_id_arr = [];
        }
        if(!$zone_id){
            $zone_id = self::$zoneId;
        }
        $item_arr = [];


        foreach($favorites_id_arr as $favorites_id){
            $item_arr = array_merge_recursive($item_arr,$this->getAllGoodsByFavoritesId($favorites_id,$page_no,$page_size,$platform,$zone_id));
        }
        Redis::setex($cache_key,3600*12,serialize($item_arr));
        return $item_arr;

    }

    public function getGoodsByFavoritesId($favorites_id,$platform = '1',$page_no='1',$page_size = '20',$zone_id = '')
    {
        $cache_key = 'goods_list'.$page_no.$page_size.$favorites_id.$platform.$zone_id;
        if(Redis::exists($cache_key) && !$data = Redis::get($cache_key)){
            return json_decode($data,true);
        }

        if(!$zone_id){
            $zone_id = self::$zoneId;
        }
        $c = $this->setPublic();
        $req = new TbkUatmFavoritesItemGetRequest;
        $req->setPlatform($platform);
        $req->setPageSize($page_size);
        $req->setAdzoneId($zone_id);

        $req->setFavoritesId($favorites_id);
        $req->setPageNo($page_no);
        $req->setFields("num_iid,title,pict_url,click_url,small_images,reserve_price,zk_final_price,user_type,provcity,item_url,seller_id,volume,nick,shop_title,zk_final_price_wap,event_start_time,event_end_time,tk_rate,status,type");
        $resp = $c->execute($req);
        $total = $resp->total_results; //总条数
        $item_lists['data'] = ($resp->results->uatm_tbk_item) ? $resp->results->uatm_tbk_item : []; //选品库里面的商品
        $item_lists['total'] = $total;
        Redis::setex($cache_key,3600*12,json_encode($item_lists));
        return $item_lists;
    }

    /**
     * @param string $page_size
     * @param string $page
     * @param string $type
     * @return array
     */
    public function getFavoritesIds($page_size = '20',$page ='1', $type = '-1')
    {
        $favorites_arr = array();
        $c = $this->setPublic();
        $req = new TbkUatmFavoritesGetRequest;
        $req->setPageNo($page);
        $req->setPageSize($page_size);
        $req->setFields("favorites_title,favorites_id,type");
        $req->setType($type);
        $resp = $c->execute($req);
        $favorites_lists = $resp->results->tbk_favorites; //选品库相当于库存
        $total = $resp->total_results; //总条数
        $max_page = ceil($total/$page_size);
        foreach($favorites_lists as $favorites_list){
            $favorites_arr[] = $this->objectToArray($favorites_list);
        }
        if($max_page > $page){
            $page++;
            $favorites_arr = array_merge_recursive($favorites_arr,$this->getFavoritesIds($page_size,(string)($page),$type));
        }
        return $favorites_arr;
    }

    /**
     * 递归取出 某个选品库下所有宝贝
     * @param $favorites_id
     * @param string $page
     * @param string $page_size
     * @param string $platform
     * @param string $zone_id
     * @return array
     */
    public function getAllGoodsByFavoritesId($favorites_id,$page='1',$page_size = '20',$platform = '1',$zone_id = '')
    {
        if(!$zone_id){
            $zone_id = self::$zoneId;
        }
        $goods_arr = array();
        $c = $this->setPublic();
        $req = new TbkUatmFavoritesItemGetRequest;
        $req->setPlatform($platform);
        $req->setPageSize($page_size);
        $req->setAdzoneId($zone_id);
        $req->setFavoritesId((string)$favorites_id);
        $req->setPageNo($page);
        $req->setFields("num_iid,title,pict_url,small_images,reserve_price,zk_final_price,user_type,provcity,item_url,click_url,nick,seller_id,volume,tk_rate,zk_final_price_wap,event_start_time,event_end_time");
        $resp = $c->execute($req);
        $goods_lists = $resp->results->uatm_tbk_item; //获取选品库中的宝贝
        $total = $resp->total_results; //总条数
        $max_page = ceil($total/$page_size);

        if(count($goods_lists)){
            foreach($goods_lists as $goods_list){
                $goods_list->favorites_id = $favorites_id;
                $goods_arr[] = $this->objectToArray($goods_list);
            }
            if($max_page > $page){
                $page++;
                $goods_arr = array_merge_recursive($goods_arr,$this->getAllGoodsByFavoritesId((string)$favorites_id,(string)$page,$page_size,$platform,$zone_id));
            }
        }
        return $goods_arr;
    }

    /**
     * 对象转数组
     * @param $obj
     * @return array
     */
    function objectToArray($obj){
        $arr = is_object($obj) ? get_object_vars($obj) : $obj;
        if(is_array($arr)){
            return array_map(array(__CLASS__,'objectToArray'), $arr);
        }else{
            return $arr;
        }
    }
}
